import { fixDuration } from './lib';
import Timer from './lib/Timer';

/**
 * 轻量版，没有依赖，录音效果是audio播放steam
 */

let audioChunks;
let rec;
let currentBlob;
const option = {
    audio: null,
    success: null
};
let timer;

/**
 * 成功后的回调
 * @callback successCallback
 */

/**
 * 录音初始化配置函数
 * @param {Object} opt - 初始化配置
 * @param {successCallback} opt.success - open成功后的回调
 * @param {Object} [opt.audio] - audio的dom实例，可选
 */

const recInitialize = (opt = {}) => {
    const { success, audio } = opt;
    option.success = success;
    if (audio) {
        option.audio = audio;
        option.audio.controls = true;
        fixDuration(option.audio);
    }
    timer = new Timer();
};

const recStop = () => {
    timer.stop();
    if (!rec || rec.state === 'inactive') return;
    console.log('stop recording');
    rec.stop();
};

const recStart = () => {
    // This will prompt for permission if not allowed earlier
    navigator.mediaDevices
        .getUserMedia({ audio: true })
        .then(stream => {
            audioChunks = [];
            // 采样率
            // const options = {
            //     audioBitsPerSecond: 128000,
            //     mimeType: 'audio/ogg'
            // };
            // rec = new MediaRecorder(stream, options);
            rec = new MediaRecorder(stream);

            if (option.audio) {
                option.audio.srcObject = rec.stream;
                console.log(option.audio.duration);
                option.audio.muted = true;
                option.audio.play();
            }

            console.log('recording...');

            timer.start();

            rec.ondataavailable = e => {
                audioChunks.push(e.data);
                if (rec.state === 'inactive') {
                    // 这样的blob没有长度
                    currentBlob = new Blob(audioChunks, { type: 'audio/x-mpeg-3' });
                    if (option.audio) {
                        option.audio.muted = false;
                        option.audio.srcObject = null;
                        option.audio.src = (window.URL || window.webkitURL).createObjectURL(currentBlob);
                        option.audio.load();
                    }
                }
            };
            rec.start();
        })
        .catch(e => console.log(e));
};

const recPlay = () => {
    if (!option.audio) return;
    option.audio.play();
};

const getBlob = () => currentBlob;

const destroy = () => {
    audioChunks = null;
    rec = null;
    currentBlob = null;
    timer = null;
};

const recPause = () => {
    timer.pause();

    if (!rec) return;
    rec.pause();

    if (!option.audio) return;
    option.audio.pause();
};

const recResume = () => {
    timer.resume();

    if (!rec) return;
    rec.resume();

    if (!option.audio) return;
    option.audio.resume();
};

const getRecDuration = () => timer.getFormatTime();

const getSliceUrl = (url, range = [0, 1]) => `${url}#t=${range[0]},${range[1]}`;

export {
    recInitialize,
    recStart,
    recStop,
    recPlay,
    recPause,
    recResume,
    getBlob,
    getSliceUrl,
    getRecDuration,
    destroy
};
